/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.bigknow.appstore.server.rpc;

import com.bigknow.appstore.server.cert.CAManager;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler;

import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManagerFactory;

/**
 * Creates a newly configured {@link ChannelPipeline} for a new channel.
 */
public class SSLServerInitializer extends ChannelInitializer<SocketChannel> {

	private SSLServer sslServer;

	public SSLServerInitializer(SSLServer sslServer) {
		this.sslServer = sslServer;
	}

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		SSLContext ctx = SSLContext.getInstance("SSL");
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

		KeyStore ks = KeyStore.getInstance("JKS");

		ks.load(CAManager.class.getResourceAsStream("ca.jks"), "atlas".toCharArray());

		kmf.init(ks, "atlas".toCharArray());
		tmf.init(ks);

		ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		SSLEngine engine = ctx.createSSLEngine();
		engine.setNeedClientAuth(true);
		engine.setUseClientMode(false);
		pipeline.addLast(new SslHandler(engine));

		pipeline.addLast(new SSLServerHandler(sslServer));
	}
}
